package com.yzh.wanandroid.repository.datasource

import android.util.Log
import androidx.paging.PagingSource
import com.yzh.wanandroid.network.retrofit.RetrofitFactory
import com.yzh.wanandroid.network.retrofit.api.UserServer
import com.yzh.wanandroid.network.retrofit.responsebean.BaseData
import com.yzh.wanandroid.network.retrofit.responsebean.BasePageData
import com.yzh.wanandroid.network.retrofit.responsebean.CollectionData

class CollectRepository : PagingSource<Int, CollectionData>() {

    private val TAG = "CollectRepository"

    private var mCurrentPage = 0

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CollectionData> {
        try {
            mCurrentPage = params.key ?: 0
            Log.i(TAG, "RetrofitFactory mCurrentPage = $mCurrentPage")
            var collectData: BaseData<BasePageData<CollectionData>> =
                RetrofitFactory.createApi(UserServer::class.java).getCollectionList(mCurrentPage)
            if (collectData.data.datas.isEmpty()) {
                return LoadResult.Page(
                    data = collectData.data.datas,
                    prevKey = null,
                    nextKey = null
                )
            }
            var nextPage =
                if (mCurrentPage < collectData.data.curPage) {
                    mCurrentPage + 1
                } else {
                    Log.i(TAG, "LoadResult mCurrentPage = null")
                    null
                }
            return LoadResult.Page(
                data = collectData.data.datas,
                prevKey = null,
                nextKey = nextPage
            )
        } catch (e: Exception) {
            Log.i(TAG, "throwable = ${e}")
            return LoadResult.Error(throwable = e)
        }
    }
}